package com.wanghua.mall.product.service.impl;

import com.wanghua.common.dto.SkuReductionDto;
import com.wanghua.common.dto.SpuBoundsDto;
import com.wanghua.common.dto.es.SkuEsModel;
import com.wanghua.common.utils.R;
import com.wanghua.mall.product.entity.*;
import com.wanghua.mall.product.openfeign.CouponFeignClient;
import com.wanghua.mall.product.openfeign.SearchFeignClient;
import com.wanghua.mall.product.openfeign.WareFeignClient;
import com.wanghua.mall.product.service.*;
import com.wanghua.mall.product.vo.SpuSaveVo;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wanghua.common.utils.PageUtils;
import com.wanghua.common.utils.Query;

import com.wanghua.mall.product.dao.SpuInfoDao;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;


@Service
public class SpuInfoServiceImpl extends ServiceImpl<SpuInfoDao, SpuInfoEntity> implements SpuInfoService {
    @Resource
    private SpuInfoDescService spuInfoDescService;
    @Resource
    private SpuImagesService spuImagesService;
    @Resource
    private AttrService attrService;
    @Resource
    private ProductAttrValueService productAttrValueService;
    @Resource
    private SkuInfoService skuInfoService;
    @Resource
    private SkuImagesService skuImagesService;
    @Resource
    private SkuSaleAttrValueService skuSaleAttrValueService;
    @Resource
    private CategoryService categoryService;
    @Resource
    private BrandService brandService;

    @Resource
    private CouponFeignClient couponFeignClient;
    @Resource
    private WareFeignClient wareFeignClient;
    @Resource
    private SearchFeignClient searchFeignClient;


    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                new QueryWrapper<>()
        );

        return new PageUtils(page);
    }

    /**
     * 保存关于商品的很多数据
     */
/*    {
        "spuName": "华为荣耀9x",
        "spuDescription": "很好",
        "categoryId": 225,
        "brandId": 1,
        "weight": 0.195,
        "publishStatus": 0,
        "description": ["https://wanghua-mall.oss-cn-hangzhou.aliyuncs.com/2021/08/25/216e3749-bc14-4ab0-8ddb-45f930a324f2_0d40c24b264aa511.jpg", "https://wanghua-mall.oss-cn-hangzhou.aliyuncs.com/2021/08/25/b2fce5f1-563c-447d-8d69-fd3fdebaa619_1f15cdbcf9e1273c.jpg"],
        "images": ["https://wanghua-mall.oss-cn-hangzhou.aliyuncs.com/2021/08/25/7a6b5341-de65-4955-8b93-017c7428ab0c_28f296629cca865e.jpg", "https://wanghua-mall.oss-cn-hangzhou.aliyuncs.com/2021/08/25/40cc0a1c-9896-4031-8c59-91dde95a065c_73ab4d2e818d2211.jpg"],
        "bounds": {
        "buyBounds": 10,
         "growBounds": 20
    },
        "baseAttrList": [{
        "attrId": 10,
        "attrValues": "KOZ-AL40",
        "showDesc": 1
    }, {
        "attrId": 11,
        "attrValues": "2021",
        "showDesc": 1
    }, {
        "attrId": 12,
        "attrValues": "金属边框",
        "showDesc": 1
    }, {
        "attrId": 13,
        "attrValues": "158.8",
        "showDesc": 1
    }, {
        "attrId": 14,
        "attrValues": "6.6英寸",
        "showDesc": 1
    }, {
        "attrId": 15,
        "attrValues": "TFT LCD（IPS）",
        "showDesc": 1
    }],
        "skuList": [{
        "attr": [{
            "attrId": 8,
            "attrName": "颜色",
            "attrValue": "黑色"
        }, {
            "attrId": 9,
            "attrName": "尺寸",
            "attrValue": "中"
        }],
        "skuName": "华为荣耀9x 黑色 中",
        "price": "7299",
        "skuTitle": "华为荣耀9x 黑色 中",
        "skuSubtitle": "【稀缺货源限量发售】每天10点08限量开抢，敬请关注！华为手机热销爆款，限量抢购；查看>",
        "images": [{
        "imgUrl": "https://wanghua-mall.oss-cn-hangzhou.aliyuncs.com/2021/08/25/7a6b5341-de65-4955-8b93-017c7428ab0c_28f296629cca865e.jpg",
                    "defaultImg": 1
        }, {
            "imgUrl": "",
            "defaultImg": 0
        }],
        "descartes": ["黑色", "中"],
        "fullCount": 10,
        "discount": 0.9,
        "countStatus": 1,
        "fullPrice": 10000,
        "reducePrice": 50,
        "priceStatus": 1,
        "userPrice": []
    }, {
        "attr": [{
            "attrId": 8,
            "attrName": "颜色",
            "attrValue": "黑色"
        }, {
            "attrId": 9,
            "attrName": "尺寸",
            "attrValue": "小"
        }],
        "skuName": "华为荣耀9x 黑色 小",
        "price":
        "skuTitle": "华为荣耀9x 黑色 小",
        "skuSubtitle": "【稀缺货源限量发售】每天10点08限量开抢，敬请关注！华为手机热销爆款，限量抢购；查看>",
        "images": [{
            "imgUrl": "https://wanghua-mall.oss-cn-hangzhou.aliyuncs.com/2021/08/25/7a6b5341-de65-4955-8b93-017c7428ab0c_28f296629cca865e.jpg",
            "defaultImg": 1
        }, {
            "imgUrl": "",
            "defaultImg": 0
        }],
        "descartes": ["黑色", "小"],
        "fullCount": 10,
        "discount": 0.9,
        "countStatus": 1,
        "fullPrice": 10000,
        "reducePrice": 50,
        "priceStatus": 1,
        "userPrice": []
    }, {
        "attr": [{
            "attrId": 8,
            "attrName": "颜色",
            "attrValue": "白色"
        }, {
            "attrId": 9,
            "attrName": "尺寸",
            "attrValue": "中"
        }],
        "skuName": "华为荣耀9x 白色 中",
        "price": "7299",
        "skuTitle": "华为荣耀9x 白色 中",
        "skuSubtitle": "【稀缺货源限量发售】每天10点08限量开抢，敬请关注！华为手机热销爆款，限量抢购；查看>",
        "images": [{
            "imgUrl": "",
            "defaultImg": 0
        }, {
            "imgUrl": "https://wanghua-mall.oss-cn-hangzhou.aliyuncs.com/2021/08/25/40cc0a1c-9896-4031-8c59-91dde95a065c_73ab4d2e818d2211.jpg",
            "defaultImg": 1
        }],
        "descartes": ["白色", "中"],
        "fullCount": 10,
        "discount": 0.9,
        "countStatus": 1,
        "fullPrice": 10000,
        "reducePrice": 50,
        "priceStatus": 1,
        "userPrice": []
    }, {
        "attr": [{
            "attrId": 8,
            "attrName": "颜色",
            "attrValue": "白色"
        }, {
            "attrId": 9,
            "attrName": "尺寸",
            "attrValue": "小"
        }],
        "skuName": "华为荣耀9x 白色 小",
        "price": "5799",
        "skuTitle": "华为荣耀9x 白色 小",
        "skuSubtitle": "【稀缺货源限量发售】每天10点08限量开抢，敬请关注！华为手机热销爆款，限量抢购；查看>",
        "images": [{
            "imgUrl": "",
            "defaultImg": 0
        }, {
            "imgUrl": "https://wanghua-mall.oss-cn-hangzhou.aliyuncs.com/2021/08/25/40cc0a1c-9896-4031-8c59-91dde95a065c_73ab4d2e818d2211.jpg",
            "defaultImg": 1
        }],
        "descartes": ["白色", "小"],
        "fullCount": 10,
        "discount": 0.9,
        "countStatus": 1,
        "fullPrice": 10000,
        "reducePrice": 50,
        "priceStatus": 1,
        "userPrice": []
    }]
    }*/
    @Transactional
    @Override
    public void saveDetail(SpuSaveVo spuSaveVo) {
        //1、保存spu基本信息
        SpuInfoEntity spuInfoEntity = new SpuInfoEntity();
        BeanUtils.copyProperties(spuSaveVo, spuInfoEntity);
        baseMapper.insert(spuInfoEntity);
        Long spuInfoEntityId = spuInfoEntity.getId();
        Long categoryId = spuInfoEntity.getCategoryId();
        Long brandId = spuInfoEntity.getBrandId();
        //2、保存spu描述图片
        List<String> description = spuSaveVo.getDescription();
        if (description != null && description.size() != 0) {
            SpuInfoDescEntity spuInfoDescEntity = new SpuInfoDescEntity();
            spuInfoDescEntity.setSpuId(spuInfoEntityId);
            spuInfoDescEntity.setDescription(String.join(",", description));
            spuInfoDescService.save(spuInfoDescEntity);
        }
        //3、保存spu图片集
        List<String> images = spuSaveVo.getImages();
        if (images != null && images.size() != 0) {
            spuImagesService.saveBatch(images.stream().map((item) -> {
                SpuImagesEntity spuImagesEntity = new SpuImagesEntity();
                spuImagesEntity.setSpuId(spuInfoEntityId);
                spuImagesEntity.setImgUrl(item);
                return spuImagesEntity;
            }).collect(Collectors.toList()));
        }
        //4、保存spu规格参数 `pms_product_attr_value`
        List<SpuSaveVo.BaseAttrList> baseAttrList = spuSaveVo.getBaseAttrList();
        if (baseAttrList != null && baseAttrList.size() != 0) {
            productAttrValueService.saveBatch(baseAttrList.stream().map((item) -> {
                ProductAttrValueEntity productAttrValueEntity = new ProductAttrValueEntity();
                productAttrValueEntity.setAttrId(item.getAttrId());
                productAttrValueEntity.setAttrValue(item.getAttrValues());
                productAttrValueEntity.setQuickShow(item.getShowDesc());
                productAttrValueEntity.setSpuId(spuInfoEntityId);
                //查出规格参数的名称和排序
                AttrEntity attrEntity = attrService.getById(item.getAttrId());
                productAttrValueEntity.setAttrName(attrEntity.getName());
                productAttrValueEntity.setAttrSort(attrEntity.getSort());
                return productAttrValueEntity;
            }).collect(Collectors.toList()));

        }
        //5、保存spu对应的sku信息
        List<SpuSaveVo.SkuList> skuList = spuSaveVo.getSkuList();
        if (skuList != null && skuList.size() != 0) {
            skuList.forEach((sku) -> {
                //5.1、保存sku基本信息
                SkuInfoEntity skuInfoEntity = new SkuInfoEntity();
                BeanUtils.copyProperties(sku, skuInfoEntity);
                skuInfoEntity.setSpuId(spuInfoEntityId);
                skuInfoEntity.setBrandId(brandId);
                skuInfoEntity.setCategoryId(categoryId);
                skuInfoEntity.setSaleCount(0L);
                sku.getImages().stream().filter(image -> image.getDefaultImg() == 1).collect(Collectors.toList());
                skuInfoEntity.setSkuDefaultImg(sku.getImages().stream()
                        .filter(image -> image.getDefaultImg() == 1)
                        .collect(Collectors.toList()).get(0).getImgUrl());
                skuInfoService.save(skuInfoEntity);

                Long skuId = skuInfoEntity.getSkuId();

                //5.2、保存sku图片信息
                skuImagesService.saveBatch(sku.getImages().stream().map((image) -> {
                    SkuImagesEntity skuImagesEntity = new SkuImagesEntity();
                    skuImagesEntity.setSkuId(skuId);
                    skuImagesEntity.setImgUrl(image.getImgUrl());
                    skuImagesEntity.setDefaultImg(image.getDefaultImg());
                    skuImagesEntity.setImgSort(0);
                    return skuImagesEntity;
                }).filter((skuImagesEntity) -> StringUtils.hasLength(skuImagesEntity.getImgUrl())).collect(Collectors.toList()));

                //5.3、保存sku的销售属性信息
                skuSaleAttrValueService.saveBatch(sku.getAttr().stream().map((attr) -> {
                    SkuSaleAttrValueEntity skuSaleAttrValueEntity = new SkuSaleAttrValueEntity();
                    skuSaleAttrValueEntity.setSkuId(skuId);
                    BeanUtils.copyProperties(attr, skuSaleAttrValueEntity);
                    return skuSaleAttrValueEntity;
                }).collect(Collectors.toList()));

                //5.4、保存sku的满减、优惠信息
                SkuReductionDto skuReductionDto = new SkuReductionDto();
                BeanUtils.copyProperties(sku, skuReductionDto);
                skuReductionDto.setSkuId(skuId);

                if (skuReductionDto.getFullCount() > 0 || skuReductionDto.getFullPrice().compareTo(new BigDecimal(0)) > 0 || sku.getUserPrice().size() != 0) {
                    couponFeignClient.saveSkuReductionDto(skuReductionDto);
                }
            });
        }

        //6、保存spu积分信息
        SpuSaveVo.Bounds bounds = spuSaveVo.getBounds();
        SpuBoundsDto spuBoundsDto = new SpuBoundsDto();
        BeanUtils.copyProperties(bounds, spuBoundsDto);
        spuBoundsDto.setSpuId(spuInfoEntityId);
        couponFeignClient.saveSpuBoundsDto(spuBoundsDto);


    }

    /**
     * 条件列表
     */
    @Override
    public PageUtils queryPageCondition(Map<String, Object> params) {
        QueryWrapper<SpuInfoEntity> queryWrapper = new QueryWrapper<>();
        //分类
        String categoryId = (String) params.get("categoryId");
        if (StringUtils.hasLength(categoryId) && !categoryId.equals("0")) {
            queryWrapper.eq("category_id", categoryId);
        }
        //品牌
        String brandId = (String) params.get("brandId");
        System.out.println(brandId);
        if (StringUtils.hasLength(brandId) && !brandId.equals("0")) {
            queryWrapper.eq("brand_id", brandId);
        }
        //状态
        String status = (String) params.get("status");
        queryWrapper.eq("publish_status", status);
        //关键字
        String key = (String) params.get("key");
        if (StringUtils.hasLength(key)) {
            queryWrapper.and((wrapper) -> {
                wrapper.like("spu_name", key).or().like("spu_description", key);
            });
        }
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                queryWrapper
        );
        return new PageUtils(page);
    }

    //商品上架
    @Transactional
    @Override
    public void productUp(Long spuId) {
        //组装数据

        //查出spu所有可以被检索的规格参数信息 TODO 简化sql
        List<ProductAttrValueEntity> productAttrValueEntityList = productAttrValueService.list(new QueryWrapper<ProductAttrValueEntity>().eq("spu_id", spuId));
        List<SkuEsModel.Attr> attrs = productAttrValueEntityList.stream().filter((productAttrValueEntity) -> attrService.getById(productAttrValueEntity.getAttrId()).getIsSearch() == 1).map((productAttrValueEntity) -> {
            SkuEsModel.Attr attr = new SkuEsModel.Attr();
            BeanUtils.copyProperties(productAttrValueEntity, attr);
            return attr;
        }).collect(Collectors.toList());
        //发送远程请求询问是否有库存
        List<Long> skuIdList = skuInfoService.list(new QueryWrapper<SkuInfoEntity>().eq("spu_id", spuId).select("sku_id")).stream().map(SkuInfoEntity::getSkuId).collect(Collectors.toList());
        Map<Long, Boolean> map = (Map<Long, Boolean>) wareFeignClient.getStockBySku(skuIdList).get("data");
        //根据spuID查出所有sku
        List<SkuInfoEntity> skuInfoEntityList = skuInfoService.getSkuBySpuId(spuId);

        List<SkuEsModel> skuEsModelList = skuInfoEntityList.stream().map((skuInfoEntity) -> {
            SkuEsModel skuEsModel = new SkuEsModel();
            BeanUtils.copyProperties(skuInfoEntity, skuEsModel);
            skuEsModel.setSkuPrice(skuInfoEntity.getPrice());
            skuEsModel.setSkuImg(skuInfoEntity.getSkuDefaultImg());
            //发送远程请求询问是否有库存
            skuEsModel.setHasStock(map.get(skuInfoEntity.getSkuId()));
            //TODO 热度评分 hotScore
            //设置分类和品牌信息
            skuEsModel.setCategoryName(categoryService.getById(skuInfoEntity.getCategoryId()).getName());
            BrandEntity brandEntity = brandService.getById(skuInfoEntity.getBrandId());
            skuEsModel.setBrandName(brandEntity.getName());
            skuEsModel.setBrandImg(brandEntity.getLogoUrl());
            //设置规格参数
            skuEsModel.setAttrs(attrs);

            return skuEsModel;
        }).collect(Collectors.toList());

        //将数据发送给es
        R r = searchFeignClient.productUp(skuEsModelList);
        if (r.getCode() == 0) {
            //成功，修改spu的状态为已上架
            SpuInfoEntity spuInfoEntity = new SpuInfoEntity();
            spuInfoEntity.setId(spuId);
            spuInfoEntity.setPublishStatus(1);
            baseMapper.updateById(spuInfoEntity);

        } else {
            //TODO 重复调用，接口幂等性
        }


    }

    /**
     * 根据skuId查询spu信息
     *
     * @param skuId
     * @return
     */
    @Override
    public SpuInfoEntity getSpuInfoBySkuId(Long skuId) {
        Long spuId = skuInfoService.getById(skuId).getSpuId();
        return baseMapper.selectById(spuId);
    }


}